<template>
  <view class="page">
    <block v-if="isLoadingFinish">
      <view class="btns">
        <text
          class="btn"
          :class="[btnType == 0 ? 'active' : '']"
          @click="switchTab(0)"
          >人员管理</text
        >
        <text
          class="btn"
          :class="[btnType == 1 ? 'active' : '']"
          @click="switchTab(1)"
          >角色管理</text
        >
      </view>
      <view class="main" v-if="btnType == 0">
        <text class="tips"
          ><text class="red">！</text
          >员工注册绑定企业后，需要审核后方能正常使用</text
        >
        <view class="cards">
          <view
            class="user"
            v-for="user in users"
            :key="user.id"
            @click="openUserEdit(user)"
          >
            <view
              class="haed"
              :class="[
                user.is_company_check && user.status
                  ? 'success'
                  : !user.status
                  ? 'error'
                  : 'warning',
              ]"
            >
              <text v-if="!user.is_company_check" class="status status-warn"
                >待审核</text
              >
              <text v-else-if="!user.status" class="status status-error"
                >禁用</text
              >
              <text
                v-else-if="user.is_company_check && user.status"
                class="status status-success"
                >使用中</text
              >
            </view>
            <view class="info">
              <image
                :lazy-load="true"
                class="cover"
                :src="user.avatar || imgBaseUrlV0 + 'temporary/mine-avatar.png'"
                mode="aspectFill"
              ></image>
              <view class="body">
                <view class="info-title">
                  {{ user.name }}{{ user.mobile ? `(${user.mobile})` : "" }}
                </view>
                <view class="sub-title"
                  >角色：<text class="role">{{
                    user.role_name || ""
                  }}</text></view
                >
                <view class="sub-title"
                  >最后登录时间：{{ user.last_login_time || "暂无" }}</view
                >
              </view>
            </view>
          </view>
        </view>
      </view>
      <view class="main padding-bottom" v-if="btnType == 1">
        <view class="cards">
          <view
            class="card"
            v-for="role in roles"
            :key="role.id"
            @click="openRoleAddAndEdit($event, role)"
          >
            <view class="info">
              <view class="info-title">
                <view class="name">
                  {{ role.role_name }}
                </view>
                <text v-if="role.is_super" class="status status-warn"
                  >系统</text
                >
                <text v-else class="status status-success">自定义</text>
              </view>
              <text class="sub-title">创建时间：{{ role.create_time }}</text>
            </view>
          </view>
        </view>
      </view>
      <view class="bottom-view" v-if="btnType == 1">
        <button
          class="btn btn-primary"
          type="primary"
          size="mini"
          @click="openRoleAddAndEdit"
        >
          新增角色
        </button>
      </view>
    </block>

    <popup-loading ref="popup"></popup-loading>
    <Message ref="message"></Message>
  </view>
</template>

<script>
import viewModule from "@/common/mixins/view-module";
import { getOperations, getCompanyUserList } from "@/common/api/operation.js";
import { getUsers } from "@/common/api/user.js";
import { getRoles } from "@/common/api/role.js";
import popupLoading from "@/components/public/loading/popup";
import { mapState } from "vuex";
import { delayFunc } from "@/common/util";

import { imgBaseUrl, imgBaseUrlV0 } from "@/common/config";
export default {
  mixins: [viewModule],
  components: {
    popupLoading,
  },
  computed: {
    ...mapState("User", ["userInfo"]),
  },
  data() {
    return {
      baseUrl: "",
      imgBaseUrlV0,
      operations: [],
      btnType: 0,
      users: [],
      userListQuery: {
        sort: {
          id: null,
        },
        limit: 20,
        page: 1,
        search: null,
        clientSide: 1,
        enterpriseId: undefined,
      },
      isLoadingUser: true,
      isLoadingFinish: false,
      roles: [],
      roleListQuery: {
        sort: {
          id: null,
        },
        limit: 20,
        page: 1,
        search: null,
        clientSide: 1,
        enterpriseId: undefined,
      },
      isLoadingRole: true,
    };
  },
  async onLoad(e) {
    this.init();
    this.onRefresh();
    this.initData();
    this.$nextTick(async () => {
      this.open();
    });
  },
  methods: {
    init() {
      // this.userListQuery.enterpriseId = this.userInfo.enterpriseId;
      // this.roleListQuery.enterpriseId = this.userInfo.enterpriseId;
    },
    onRefresh() {
      uni.$on("refresh-permission-user-list", (data) => {
        this.userListQuery.page = 1;
        this.users = [];
        this.isLoadingUser = false;
        this.getUsers();
      });
      uni.$on("refresh-permission-role-list", (data) => {
        this.roleListQuery.page = 1;
        this.roles = [];
        this.isLoadingRole = false;
        this.getRoles();
      });
    },
    initData() {
      this.getOperations();
      this.switchTab(0);
    },
    switchTab(btnType) {
      this.btnType = btnType;
      this.getUsers();
      this.getRoles();
    },
    async getOperations() {
      this.operations = [];
      await getOperations({
        permissionName: "MobileEnterpriseRoleManagement",
        clientSide: 1,
      })
        .then((response) => {
          this.operations.push(...response);
        })
        .catch(() => {});
      this.close();
    },

    open() {
      this._time = +new Date();
      this.$refs.popup && this.$refs.popup.open();
    },
    async close() {
      let now = +new Date();
      let time = this._time;
      let t = now - time;
      if (t <= 1000 * 0.5) {
        await delayFunc(500 - t);
      }
      this.isLoadingFinish = true;
      this.$refs.popup && this.$refs.popup.close();
    },
    getUsers() {
      if (!this.isFirstLoadingUser) {
        this.open();
        this.isFirstLoadingUser = true;
      }
      return getUsers(this.userListQuery)
        .then((res) => {
          this.close();
          let data = res.data || [];
          // const { list, total } = response;
          this.users = data;
          if (this.isLoadingUser) {
            uni.hideLoading();
          }
          uni.stopPullDownRefresh();
        })
        .catch(() => {
          this.close();
          if (this.isLoadingUser) {
            uni.hideLoading();
          }
          uni.stopPullDownRefresh();
        });
    },
    openUserEdit(user) {
      if (user.id === this.userInfo.id) {
        return this.message.error("无法编辑自己");
      }
      uni.navigateTo({
        url: "/pages/user-edit/user-edit?userId=" + user.id,
      });
      // if (!user.is_company_check) {
    },
    getRoles() {
      // if (this.isLoadingRole) {
      //   uni.showLoading({
      //     title: "加载中",
      //     mask: false,
      //   });
      // }
      return getRoles(this.roleListQuery)
        .then((res) => {
          let data = res.data || [];
          this.roles = data;

          if (this.isLoadingRole) {
            uni.hideLoading();
          }
          uni.stopPullDownRefresh();
        })
        .catch(() => {
          if (this.isLoadingRole) {
            uni.hideLoading();
          }
          uni.stopPullDownRefresh();
        });
    },
    openRoleAddAndEdit(e, role = {}) {
      if (role.is_super) return this.message.error("超级管理员无法编辑");
      let len = this.roles.filter((item) => item.enterpriseId).length;
      if (len < 5 && role) {
        this.$Router.push({
          path: "/pages/role-add-and-edit/role-add-and-edit",
          query: {
            id: role.id || "",
            name: role.role_name || "",
          },
        });
      } else {
        return this.message.error("最多只能自定义5个角色");
      }
    },
  },
  async onReachBottom() {},
  onPullDownRefresh() {
    this.getUsers();
    this.getRoles();
    uni.stopPullDownRefresh();
  },
};
</script>

<style lang="stylus" scoped>
@import '~@/common/stylus/variable';
@import '~@/common/stylus/mixins';

page, .page {
  min-height: calc(100vh - var(--window-top));
  background: linear-gradient(180deg, #0d1523 0%, #102945 100%);
  padding-bottom: 30rpx;
}

.btns {
  padding: 30rpx 24rpx;
  display: flex;
  flex-direction: row;

  .btn {
    flex: 1;
    text-align: center;
    background-color: #fff;
    color: #3f7dff;
    font-size: 32rpx;
    height: 72rpx;
    line-height: 72rpx;
    border-radius: 0;
    border-radius: 8rpx 0px 0px 8rpx;

    &:last-child {
      margin-right: 0;
      border-radius: 0 8rpx 8rpx 0;
    }

    &.active {
      background-color: #3f7dff;
      /* background-image: linear-gradient(-15deg, #79c0ff, #3575df) !important; */
      color: #fff;
    }
  }
}

.main {
  padding: 0 30rpx;

  >.tips {
    display: block;
    padding: 0;
    margin-bottom: 30rpx;
  }

  .cards {
    .user {
      background: #1A3156;
      border-radius: 8rpx;
      padding: 0 20rpx;
      margin-bottom: 20rpx;

      > .haed {
        position: relative;
        line-height: 78rpx;
        margin: 0 20rpx;
        font-size: 28rpx;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: bold;
        border-bottom: 1rpx solid #d8d8d8;
        text-indent: 30rpx;

        &.success {
          color: color-success;

          &:after {
            background: color-success;
          }
        }

        &.warning {
          color: color-warning;

          &:after {
            background: color-warning;
          }
        }

        &.error {
          color: color-danger;

          &:after {
            background: color-danger;
          }
        }

        &:after {
          position: absolute;
          content: '';
          width: 10rpx;
          height: 10rpx;
          left: 0;
          top: 0;
          bottom: 0;
          border-radius: 10rpx;
          margin: auto;
        }
      }

      > .info {
        display: flex;
        padding: 16rpx 0 20rpx;
        align-items: center;

        > .cover {
          flex: 0 0 120rpx;
          width: 120rpx;
          height: 120rpx;
          border-radius: 100rpx;
          margin-right: 20rpx;
        }

        > .body {
          flex: 1;

          > .info-title, > .sub-title {
            font-size: 28rpx;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            line-height: 46rpx;
            color: color-white;
          }

          .role {
            color: color-white;
          }
        }
      }
    }

    .card {
      padding-bottom: 20rpx;
      // border-bottom: 3rpx solid #eee;
      margin-bottom: 20rpx;
      display: flex;
      flex-direction: row;
      background-color: #1A3156;
      border-radius: 5rpx;

      &:last-child {
        margin-bottom: 0;
        border-bottom: 0;
      }

      .info {
        flex: 1;
        padding: 0 20rpx;

        .info-title {
          display: flex;
          line-height: 60rpx;
          // font-weight: 700;
          font-size: 28rpx;
          color: #fff;
          padding-top: 12rpx;

          >.name {
            flex: 1;
          }

          >.status {
            flex: 0 0 auto;
            height: 40rpx;
            line-height: 36rpx;
            margin-top: 8rpx;
            border-radius: 4rpx;
          }

          .status-warn, .status-error, .status-success {
            display: inline-block;
            margin-left: 10rpx;
            padding: 0 10rpx;
            background-color: #D5E6FF;
            color: #288EFC;
            font-size: 22rpx;
          }

          .status-warn {
            background-color: #FFE9E0;
            color: #F19149;
          }

          .status-error {
            background-color: #dd524d;
            color: #fff;
          }
        }

        .sub-title {
          display: block;
          line-height: 40rpx;
          font-size: 26rpx;
          color: #fff;
          margin-top: 6rpx;
        }
      }
    }
  }

  &.padding-bottom {
    padding-bottom: 70rpx;
  }
}

.bottom-view {
  position: fixed;
  bottom: 20rpx;
  left: 0;
  height: 100rpx;
  width: 100%;
  text-align: center;
  padding: 0 24rpx;

  .btn {
    display: block;
    width: 100%;
    height: 90rpx;
    line-height: 86rpx;
    font-size: 28rpx;
    margin: auto;
  }
}
</style>